package com.anrongtec.zcpt.logo;

import android.app.ProgressDialog;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.anrongtec.zcpt.R;
import com.anrongtec.zcpt.authentication.AuthorizeLoginObserver;
import com.anrongtec.zcpt.authentication.AuthorizeReceiver;
import com.anrongtec.zcpt.authentication.BillOperation;
import com.anrongtec.zcpt.base.BaseActivity;
import com.anrongtec.zcpt.base.DDApp;
import com.anrongtec.zcpt.callback.StringDialogCallback;
import com.anrongtec.zcpt.constant.PreferenceKey;
import com.anrongtec.zcpt.interfaces.HttpUtil;
import com.anrongtec.zcpt.interfaces.ShuJuURL;
import com.anrongtec.zcpt.interfaces.URLConstants;
import com.anrongtec.zcpt.interfaces.module.JsonDataRestult;
import com.anrongtec.zcpt.interfaces.theInferfaces.HttpInterfaces;
import com.anrongtec.zcpt.module.LoginIP;
import com.anrongtec.zcpt.module.LoginUserInfo;
import com.anrongtec.zcpt.module.User;
import com.anrongtec.zcpt.module.XdjaBill;
import com.anrongtec.zcpt.util.GsonUtil;
import com.anrongtec.zcpt.util.JsonParse;
import com.anrongtec.zcpt.util.LogUtil;
import com.anrongtec.zcpt.util.RSAUtils;
import com.art.base.util.DeviceFactory;
import com.art.base.util.DialogUtil;
import com.art.base.util.FileUtils;
import com.art.base.util.PreferenceUtils;
import com.art.base.util.ToastShow;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/1/26.
 */

public class MyLoginActivity extends BaseActivity {
	private AuthorizeReceiver authorizeReceiver;
	private String username;
	private String password;
	private int currentType = 1;
	private static final int SHOW_LOGIN_VIEW = 1;
	private static final int SHOW_LOGIN_CONFIG=5;
	private User jsonData;
	private ProgressDialog proDialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleShow(false);
		setContentView(R.layout.activity_logo);
		proDialog = DialogUtil.createLoadingDialog(this, "请稍候...");

//		LoginJiLin(null);

	}

	@Override
	protected void onStart() {
		super.onStart();
		iniAuth();
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case SHOW_LOGIN_VIEW:
					ToastShow.makeToast(MyLoginActivity.this,"登录失败");
					proDialog.cancel();
					finish();
					break;
				case SHOW_LOGIN_CONFIG:
					jsonData= (User) msg.obj;
//					getConfig();
					getTheShowPermission();
					break;

			}
		}
	};
	private void iniAuth() {
		//获取票据
		authorizeReceiver = new AuthorizeReceiver();
		AuthorizeReceiver.registerObserver(new Oberver());
		//接收票据广播
		IntentFilter filter = new IntentFilter();
		filter.addAction("com.anrongtec.zcpt");
		//注册广播接收
		registerReceiver(authorizeReceiver,filter);

		String billInfoByCurosr = null;
		try {
			billInfoByCurosr = BillOperation.getBillInfoByCurosr(MyLoginActivity.this);
			if(!TextUtils.isEmpty(billInfoByCurosr)){
				uaslogin(billInfoByCurosr);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ToastShow.makeToast(MyLoginActivity.this,e.getMessage());
		}

	}
	 class  Oberver implements AuthorizeLoginObserver {
		@Override
		public void loginSuccess() {
			String billInfoByCurosr = null;
			try {
				billInfoByCurosr = BillOperation.getBillInfoByCurosr(MyLoginActivity.this);
				if(!TextUtils.isEmpty(billInfoByCurosr)){
					uaslogin(billInfoByCurosr);
				}
			} catch (Exception e) {
				e.printStackTrace();
				ToastShow.makeToast(MyLoginActivity.this,e.getMessage());
			}


		}
	}
	String json = "{\n" +
			"\t\"flag\": \"验证结果\",\n" +
			"\t\"message\": \"提示信息\",\n" +
			"\t\"id\": \"暂不使用\",\n" +
			"\t\"userInfo\": {\n" +
			"\t\t\"id\": \"1\",\n" +
			"\t\t\"name\": \"姓名\",\n" +
			"\t\t\"sex\": \"性别\",\n" +
			"\t\t\"code\": \"111116\",\n" +
			"\t\t\"depcode\": \"单位编码\",\n" +
			"\t\t\"depid\": \"单位ID\",\n" +
			"\t\t\"identifier\": \"身份证号\",\n" +
			"\t\t\"mobile\": \"手机号\",\n" +
			"\t\t\"police\": \"警种\",\n" +
			"\t\t\"position\": \"职级\",\n" +
			"\t\t\"effectivedate\": \"票据有效期\",\n" +
			"\t\t\"limits\": [\"终端访问权限\", \"终端访问权限\"]\n" +
			"\t}\n" +
			"}";
	private  void uaslogin(String bill){
		try {
			HttpInterfaces.getXdjaBillInfo(ShuJuURL.GET_BILL, bill, new com.anrongtec.zcpt.interfaces.theInferfaces.callback.StringDialogCallback() {
				@Override
				public void onSuccess(String s, Call call, Response response) {
					Log.e("xdja",s);
					if(!TextUtils.isEmpty(s)){
						XdjaBill xdjaBill = JsonParse.parseJsonWithGson(s, XdjaBill.class);

						if(xdjaBill!=null &&xdjaBill.getUserInfo()!=null){

							LoginJiLin(xdjaBill);

						}else{
							ToastShow.makeToast(MyLoginActivity.this,xdjaBill.getMessage());
//							finish();
						}

					}



				}
				@Override
				public void onError(Call call, Response response, Exception e) {
					//super.onError(call, response, e);
					XdjaBill xdjaBill = JsonParse.parseJsonWithGson(json, XdjaBill.class);
					LoginJiLin(xdjaBill);

					proDialog.cancel();
				}
			});

		}catch (Exception e){
			e.printStackTrace();
		}

	}

	private void LoginJiLin(XdjaBill xdjaBill) {
        username = xdjaBill.getUserInfo().getCode();
//		username ="999993";
		password= "111111";
		RSAUtils rsa = RSAUtils.create();
		String encodeUserName = rsa.encodeByPublicKey(username, RSAUtils.pubKey);//
		String encodePassWd = rsa.encodeByPublicKey(password, RSAUtils.pubKey);
		Login(encodeUserName, encodePassWd);
	}

	/**
	 * 登录
	 *
	 * @param encodeUserName 账号
	 * @param encodePassWd   密码
	 */
	private void Login(String encodeUserName, String encodePassWd) {
		// 初始化baseinfo
		DDApp.dApp.initBaseInfo();
		String number = DeviceFactory.getInstance(this).getPhoneNumber();

		String secretid = DeviceFactory.getInstance(this).getCardId();
		Log.e("number",number+"");
		// 组装登录请求的json
		final String json = GsonUtil.toLoginJson(encodeUserName, encodePassWd,number,secretid,
				currentType);
		LogUtil.e(json);

		HttpUtil.post(json, new StringDialogCallback(this, "正在登录...") {

			@Override
			public void onResponse(boolean arg0, String arg1, Request arg2, Response
					arg3) {
				LogUtil.e("用户信息" + arg1);
				JsonDataRestult<User> jsonData = GsonUtil.decode(arg1, new
						TypeToken<JsonDataRestult<User>>() {
						}.getType());
				if (URLConstants.RetCode.SUCCESS.equals(jsonData.getRetCode())) {
					if (jsonData.getData() != null) {
						handler.sendMessage(handler.obtainMessage(SHOW_LOGIN_CONFIG,jsonData.getData()));
					} else {
						handler.sendEmptyMessage(SHOW_LOGIN_VIEW);
					}
				} else {
					ToastShow.shortMessage(jsonData.getRetMsg());
					handler.sendEmptyMessage(SHOW_LOGIN_VIEW);

				}
			}
			@Override
			public void onError(boolean isFromCache, Call call, Response response,
								Exception e) {

				if (response == null) {
					ToastShow.shortMessage(getString(R.string.alert_failed_connect));
				}
				proDialog.cancel();
				handler.sendEmptyMessage(SHOW_LOGIN_VIEW);
				super.onError(isFromCache, call, response, e);
			}
		});
	}
	/*
	* 1.
	* 获取分离app 需要的ip*/
	private void getConfig(){
		HttpInterfaces.getConfig(ShuJuURL.GET_CONFIG+"code="+username, new com.anrongtec.zcpt.interfaces.theInferfaces.callback.StringDialogCallback(this,"正在加载,稍后....") {
			@Override
			public void onSuccess(String s, Call call, Response response) {
				LoginIP loginIP = JsonParse.parseJsonWithGson(s, LoginIP.class);
//				if(null!=loginIP){
//					initConfig(loginIP);
//				}
				if(!TextUtils.isEmpty(s)){
					getUserInfos(s);

				}

			}

			@Override
			public void onError(Call call, Response response, Exception e) {
				super.onError(call, response, e);
				ToastShow.makeToast(MyLoginActivity.this,e.getMessage());
				proDialog.cancel();
				finish();
				Log.e("ip_erro",e.getMessage());
			}
		});
	}
	String ip,webInfo,upLoad,pushIp,imgCom;
	String sessionkey;
	private void initConfig(LoginIP loginIP) {
		for(int i=0;i<loginIP.getData().size();i++){

			switch (loginIP.getData().get(i).getName()){
				case "jwt":
					ip = loginIP.getData().get(i).getUrl();
					Log.e("ip=======" , ip);
					break;
				case "static":
					webInfo = loginIP.getData().get(i).getUrl();
					Log.e("static=======" , webInfo);
					break;
				case "push":
					pushIp = loginIP.getData().get(i).getUrl();
					Log.e("push=======" , pushIp);
					break;
				case "upload":
					upLoad = loginIP.getData().get(i).getUrl();
					Log.e("upload=======" , upLoad);
					break;
				case "th_imgcmp":
					imgCom = loginIP.getData().get(i).getUrl();
					Log.e("th_imgcmp=======" , imgCom);
				default:
					break;
			}

		}
//		getUserInfos();
	}

	/**
	 * 2,通过sessionkey 获取信息内容
	 */
	private void getUserInfos(final String ipjson) {
		//保存sessionkey
		// //add by lina  保存登录相关信息
		String imei = DeviceFactory.prefs.getString("prefs_device_id","");
		String imsi = DeviceFactory.prefs.getString("prefs_imsi_code","");
		String uuid = DeviceFactory.prefs.getString("prefs_device_uuid","");
		sessionkey = imei+imsi+uuid;
		HttpInterfaces.getSessionInfo(ShuJuURL.GET_INFO_BY_SEESIONKEY, sessionkey, new com.anrongtec.zcpt.interfaces.theInferfaces.callback.StringDialogCallback(MyLoginActivity.this,"......") {
			@Override
			public void onSuccess(String s, Call call, Response response) {
				if(!TextUtils.isEmpty(s)&&!s.equals("1")){
					//保存用户的其他信息
					saveloginInfo(s,ipjson);
				}
			}
			@Override
			public void onError(Call call, Response response, Exception e) {
				super.onError(call, response, e);
				ToastShow.makeToast(MyLoginActivity.this,e.getMessage());
				proDialog.cancel();
				finish();
			}
		});

	}
	/**
	 * 保存用户信息
	 * @param userinfo
	 */
	private void saveloginInfo(String userinfo,String ipjson) {
		String accountId = jsonData.getAccountId();//当前的用户名
		// 保存当前用户的用户名
		PreferenceUtils.getInstance(MyLoginActivity.this).save(PreferenceKey.ACCOUNT_ID,
				accountId);
		DDApp.dApp.setCurrentUser(jsonData);

		//还要保存原来的ip
		LoginUserInfo loginUserInfo = JsonParse.parseJsonWithGson(userinfo, LoginUserInfo.class);
		try {
			JSONObject jsonObject = new JSONObject(ipjson);

			jsonObject.put("username",username);
			jsonObject.put("password",password);
			jsonObject.put("dwdm",loginUserInfo.getOrganizationId());

			String s = jsonObject.toString();
			String s1=s.replace("\\","");
			FileUtils.saveFile(s1,"loginIP.txt");
		} catch (JSONException e) {
			e.printStackTrace();
		}
		LoginIP loginIP = JsonParse.parseJsonWithGson(ipjson, LoginIP.class);
		if(null!=loginIP){
			initConfig(loginIP);
		Map<String,String> map = new HashMap<>();
		map.put("username",username);//警号
		map.put("password",password);
		map.put("ip",ip);
		map.put("pushIp",pushIp);
		map.put("webInfo",webInfo);
		map.put("upLoadIp",upLoad);
		map.put("imagCom",imgCom);
		map.put("dwdm",loginUserInfo.getOrganizationId());

		String json = GsonUtil.toJson(map);
		Log.e("jsonmap",json);


		//保存用户信息
			FileUtils.saveFile(json,"loginInfo.txt");}
			FileUtils.saveFile(userinfo,"userInfo.txt");
		FileUtils.saveFile(sessionkey,"sesionkey.txt");

		//通过sessionkey 获取当前人员登录信息
		//===========================end====
		startActivity(MainActivity.class);
		proDialog.cancel();
		finish();
	}

	@Override
	protected void onDestroy() {
		//取消广播
		unregisterReceiver(authorizeReceiver);
		super.onDestroy();
	}

	private boolean xdjaSSO;
	private void getTheShowPermission() {
		//获取是新链路还是老链路
		HttpInterfaces.getPermissions(ShuJuURL.GET_PERMISSIONS+"code="+username, new com.anrongtec.zcpt.interfaces.theInferfaces.callback.StringDialogCallback(this,"正在加载,稍后....") {
			@Override
			public void onSuccess(String s, Call call, Response response) {
				UserPermissons userPermissons = JsonParse.parseJsonWithGson(s, UserPermissons.class);
				List<String> permissions = userPermissons.getString();
				for (String string : permissions) {
					switch (string) {
						case "xdjaSSO"://是否对接信达统一认证
							LogUtil.e(string);
							xdjaSSO = true;
							break;
					}
				}
				getConfig();
			}

			@Override
			public void onError(Call call, Response response, Exception e) {
				super.onError(call, response, e);
			}
		});

	}
}
